package com.dyna.demo.feign.service.impl;

import com.dyna.constants.ModuleErrorCodeConstants;
import com.dyna.core.exception.CustomException;
import com.dyna.demo.feign.service.OpenFeignService;
import com.dyna.domain.resp.R;
import com.dyna.foundation.domain.entity.SysUser;
import com.dyna.foundation.domain.resp.SysUserResp;
import com.dyna.foundation.feign.FoundationUserApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Optional;

@Slf4j
@Service
public class OpenFeignServiceImpl implements OpenFeignService {

    @Resource
    private FoundationUserApi foundationUserApi;

    @Override
    public SysUserResp getUserInfoById(Long userId) {
        R<SysUserResp> r = foundationUserApi.getUser(userId);
        return Optional.ofNullable(r).map(R::getData).orElseThrow(() -> new CustomException(ModuleErrorCodeConstants.USER_NOT_EXISTS.getMsg()));
    }

    @Override
    public SysUser getUserInfoByUsername(String username) {
        R<SysUser> r = foundationUserApi.getUserByUsername(username);
        return Optional.ofNullable(r).map(R::getData).orElseThrow(() -> new CustomException(ModuleErrorCodeConstants.USER_NOT_EXISTS.getMsg()));
    }

    /**
     * 测试远程调用异常
     * 1. R.data当删除用户失败，仅removeById(uid);返回data结果为false，那么R返回success=true
     * 2. R.data当业务逻辑中抛出异常，那么R返回success=false
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean testException(Long userId) {
        R<Boolean> r = foundationUserApi.testDel(userId);
        Optional.ofNullable(r).map(R::getData).orElseThrow(() -> new CustomException("删除用户失败11"));
        int i = 1/0;
        return Boolean.TRUE;
    }

}
